<template>
  <div class="live-room">
    <div class="video-box">
<!--       <video v-if="playFlag" id="my-video" class="video-js" x-webkit-airplay="allow" webkit-playsinline controls preload="auto">
          <source :src="pullUrl" type="video/mp4">
      </video> -->
      <video v-show="playFlag" id='myvideo' class="video-js vjs-default-skin" controls>
          <source :src="pullUrl">    
      </video>
      <img class="cover" :src="channel.trailerCover">
      <div class="video-num">
        <div class="back" @click="goBack"><img src="../../assets/images/back.png"></div>
        <div class="num">
          <van-icon name="eye-o" />
          <span>{{ setting.currentAudience || 0 }}人观看</span>
        </div>
      </div>
      <div v-if="!playFlag" class="play" @click="toPlay"><img src="../../assets/images/play.png"></div>
    </div>
    <div class="video-text">
      <div class="inner">
        <span>{{ setting.scrollSubtitle }}</span>
        <span>{{ setting.scrollSubtitle }}</span>
      </div>
    </div>
    <van-swipe v-if="scrollBarImg.length>0" class="live-room__swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item v-for="(item, index) in scrollBarImg" :key="index"><img :src="item"></van-swipe-item>
    </van-swipe>
    <van-tabs :active="active" background="transparent" line-width="24" animated>
      <van-tab title="聊天互动">
        <div class="chat-container">
          <div class="top-box">
            <van-icon name="volume-o" />
            <div class="top">
              <div class="inner">
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
              </div>
            </div>
          </div>
          <div id="chat-list">
            <div class="leave-message" v-for="item in mesList" :key="item.idClient">
              <div class="leave-message__avatar">
                <van-image round width="46px" height="46px" :src="item.fromAvatar" />
              </div>
              <div class="leave-message__content">
                <div class="leave-message__nickname">
                  <span>{{ item.fromNick }}</span>
          <!--         <van-image
                    v-show="admin"
                    class="leave-message__tag-admin"
                    width="48px"
                    fit="contain"
                    :src="require('./assets/tag-admin.png')"
                  /> -->
                </div>
                <span class="leave-message__message">
                  <!-- <span class="leave-message__top" v-show="top">[置顶]</span> -->
                  <span v-if="item.type=='text'">{{ item.text }}</span>
                  <span v-if="item.type=='image'"><img :src="item.file.url" style="max-width:200px; max-height:200px;"></span>
                </span>
                <span class="leave-message__datetime">{{ item.time | dateFormat }}</span>
          <!--       <div class="leave-message__actions">
                  <span class="leave-message__action">删除评论</span>
                  <span v-show="!top" class="leave-message__action leave-message__action--top">置顶</span>
                  <span v-show="top" class="leave-message__action">取消置顶</span>
                </div> -->
              </div>
              
            </div>
            <!-- <leave-message v-for="item in mesList" :key="item.idClient" :nickname="item.fromNick" :fromAvatar="item.fromAvatar" :time="item.time" admin top>{{ item.text }}</leave-message> -->
          </div>
          <div class="chat-action-bar">
            <div class="chat-btn">
              <van-icon name="chat-o" size="18" />
            </div>
            <div class="chat-input">
              <van-field v-model="message" placeholder="发消息..." @keyup.enter="sendMsg"/>
            </div>
            <div class="chat-btn chat-btn-ml" @click="showEmoji">
              <van-icon name="smile-o" size="18" />
            </div>
            <div class="chat-btn chat-btn-ml">
              <van-icon name="add-o" size="18" />
<!--               <a-upload style="opacity:0;"
                name="file"
                action="https://api.51ysscw.life/interface/api/commons/file/uploadImg"
                @change="handleChange"
              >
                <a-button></a-button>
              </a-upload> -->
              <input id="file" type="file" style="opacity:0; position:absolute;top:0; left:0;" @change="getImg" />
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="活动介绍">
        <div class="top-boxs">
          <van-icon name="volume-o" />
            <div class="top">
              <div class="inner">
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
              </div>
            </div>
        </div>
        <div style="height:662px; background-color:#eee;"></div>
      </van-tab>
      <van-tab title="在线抢藏">
        <div class="top-boxs">
          <van-icon name="volume-o" />
            <div class="top">
              <div class="inner">
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
                <span>首次立体浮雕牛、首次金银双金属材质、首次金银定位浮雕工艺</span>
              </div>
            </div>
        </div>
        <div class="form-box">
          <div class="form-tit">姓名<span class="red">*</span></div>
          <div class="form-li">
            <van-field v-model="name" />
          </div>
          <div class="form-tit">订购数量<span class="red">*</span></div>
          <div class="form-li">
            <van-field v-model="num" type="digit" />
          </div>
          <van-button class="submit" type="danger" @tap="toSubmit">立即提交</van-button>
        </div>
      </van-tab>
    </van-tabs>
    <UserRed v-show="isRedShow"
      :dTime="ReddTime"
      :redStatus="redStatus" />
    <chat-emoji
      v-show="isEmojiShown"
      v-on:add-emoji="addEmoji"
      v-on:hide-emoji="hideEmoji"
    ></chat-emoji>

    <div class="red-box" @click="isRedShow=true">
      <img src="../../assets/images/red.png">
    </div>

  </div>
  
</template>

<script>
import { Swipe, SwipeItem, Tab, Tabs } from "vant";
import UserRed from '../../components/live/userred'
import ChatContainer from "../../components/live/ChatContainer";
import http from "@/utils/request";
import SDK from '@/sdk/NIM_Web_SDK_v6.1.0';
import LeaveMessage from "../../components/live/LeaveMessage";
import ChatEmoji from './ChatEmoji'
import {setToken} from "@/utils/auth";
import $api from "@/api/index";

var chatroom = null;
var scrollTimer = null;
let initCount = 1;
let player = null;
export default ({
  name: "LiveRoom",
  components: {
    UserRed,
    ChatContainer,
    LeaveMessage,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    ChatEmoji
  },
  // setup() {
  //   const active = ref(0);
  //   return { active };
  // },
  data() {
    return {
      isRedShow: false,
      redStatus:1,//0未设置红包 3已抢过  4未抢过，已被抢完   redStatus:1可抢——hasOpenRed:1抢前 2抢中 3抢后
      ReddTime:true,//发红包的头像定位
      name: '',
      num: 1,
      message: '',
      account: 'oeQF_xLFpZL978720OEGh1P4xy6E',
      channel: {},
      setting: {},
      scrollBarImg: [],
      mesList: [],
      userInfo: {},
      openId: '',
      imageUrl: '',
      isEmojiShown: false,
      pullUrl: '',
      playFlag: false
    }
  },
  created(){
    //https://h5.51ysscw.life/?openId=oeQF_xLFpZL978720OEGh1P4xy6E#/home
    //http://localhost:8088/?openId=oeQF_xLFpZL978720OEGh1P4xy6E#/liveroom?id=1f405bff1c574bbd8f37d1db8ece81f4
    let openId = this.$route.query.openId;
    if(openId){
      setToken(openId)
    }
    let cid = this.$route.query.id;
    if(cid){
      localStorage.setItem('cid', cid);
    }
    let url = location.href;
    console.log(url)
    if(url.indexOf('openId')==-1){
      location.href = "https://api.51ysscw.life/interface/api/mobile/public/wxUserInfo/exclude/authorize"
    }
    else{
      let str = url.split("#")[0];
      console.log(str)
      let openId = str.split("openId=")[1]
      console.log(str.split("openId=")[1])
      this.openId = openId;
      
      // setToken(openId);
      // console.log(openId)
        $api.aboutApi.wxUserInfo({}).then((res)=>{
          this.userInfo = res.data;
          let id = localStorage.getItem('cid');
          console.log(id)
          //直播间信息
          http.request({
              url: "/api/mobile/public/channel/exclude/getChannelInfo",
              method: "get",
              params: {
                channelId: id
              }
          }).then((res)=>{
            this.channel = res.data.channel;
            this.setting = res.data.marketingSettings;
            this.scrollBarImg = res.data.marketingSettings.scrollBarImg;
            this.pullUrl = res.data.channel.rtmpPullUrl;
            let roomid = res.data.chatroom.roomid;
            http.request({
                url: "/api/mobile/chatroom/requestAddr",
                method: "get",
                params: {
                  roomid: roomid
                }
            }).then((res)=>{
              console.log(res)
              this.init(roomid, res.data.addr);
            });
          });
       })
    }
  },
  methods:{
    init(roomid, addr){
      // 匿名方式登录
      let self = this;
      let accid = this.userInfo.neteaseUserInfo.accid;
      let token = this.userInfo.neteaseUserInfo.token;
      chatroom = SDK.Chatroom.getInstance({
        appKey: 'f8a1497297ff9bcef226adcc3261ea04',
        account: accid,
        token: token,
        chatroomId: roomid,
        chatroomAddresses: addr,
        onconnect: function(obj){
          console.log(obj)
          // 该处chatroom为全局生成的实例
          //window.account = chatroom.account
           chatroom.getHistoryMsgs({
              msgTypes: ['text', 'image'],
              done: function(error, obj){
                console.log(obj)
                let msgs = obj.msgs;
                let mesList = msgs.reverse();
                self.mesList = mesList;
                self.scrollDown();
                //self.getHistoryMsgsDone(error, obj)
                chatroom.getChatroomMembers({
                  guest: false,
                  limit: 100,
                  done: function(error, obj){
                    console.log(obj.members)
                    // let members = obj.members;
                    // for(let i in members){
                    //   for(let j in mesList){

                    //   }
                    // }
                  }
                });
              }
            })
        },
        onwillreconnect: function(obj){
          console.log('即将重连');
          console.log(obj.retryCount);
          console.log(obj.duration);
        },
        ondisconnect: function(error){
          console.log('丢失连接');
          console.log(error);
          if (error) {
            switch (error.code) {
              // 账号或者密码错误, 请跳转到登录页面并提示错误
              case 302:
                break;
              // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
              case 417:
                break;
              // 被踢, 请提示错误后跳转到登录页面
              case 'kicked':
                break;
              default:
                break;
            }
          }
        },
        onerror: function(error){
          console.log(error);
        },
        onmsgs: function(res){
          console.log(res)
          for(let i in res){
            if(res[i].type=="text"){
              self.mesList.push(res[i]);
              self.initCount = 1;
              self.scrollDown();
            }
          }
        }
      });
    },
    sendMsg(){
      let self = this;
      var msg = chatroom.sendText({
        text: this.message,
        done: function(error, msg) {
          self.mesList.push(msg);
          self.message = '';
          self.initCount = 1;
          self.scrollDown();
        }
      });
    },
    sendImg(){
      chatroom.sendFile({
        type: 'image',
        fileInput: "file",
        uploadprogress: function(obj) {
          console.log('文件总大小: ' + obj.total + 'bytes');
          console.log('已经上传的大小: ' + obj.loaded + 'bytes');
          console.log('上传进度: ' + obj.percentage);
          console.log('上传进度文本: ' + obj.percentageText);
        },
        uploaddone: function(error, file) {
          console.log('上传' + (!error?'成功':'失败'), error, file);
        },
        beforesend: function(msg) {
          console.log('正在发送聊天室image消息, id=' + msg.idClient);
        },
        done: function(msg){
          console.log(msg)
        }
      });
    },
    getImg(e){
      let file = e.target.files[0];
      chatroom.sendFile({
        type: 'image',
        blob: file,
        uploadprogress: function(obj) {
          console.log('文件总大小: ' + obj.total + 'bytes');
          console.log('已经上传的大小: ' + obj.loaded + 'bytes');
          console.log('上传进度: ' + obj.percentage);
          console.log('上传进度文本: ' + obj.percentageText);
        },
        uploaddone: function(error, file) {
          console.log('上传' + (!error?'成功':'失败'), error, file);
        },
        beforesend: function(msg) {
          console.log('正在发送聊天室image消息, id=' + msg.idClient);
        },
        done: function(msg){
          console.log(msg)
        }
      });
    },
    showEmoji () {
      this.isEmojiShown = true
    },
    hideEmoji () {
      this.isEmojiShown = false
    },
    addEmoji (emojiName) {
      this.message += emojiName
      this.hideEmoji()
    },
    setAdmin(){
      chatroom.markChatroomManager({
        account: this.account,
        isAdd: true,
        done: function(error, obj) {
          console.log('添加聊天室管理员' + (!error?'成功':'失败'), error, obj.member);
        }
      });
    },
    scrollDown(){
      let dom = document.getElementById('chat-list');
      if (!dom) {
        return
      }
      let maxCount = 5
      
      let pos = Math.max(dom.scrollHeight - dom.clientHeight, 888888);
      dom.scrollTop = pos;
      if (initCount < maxCount) {
        clearTimeout(scrollTimer)
        scrollTimer = setTimeout(() => {
          initCount++
          this.scrollDown(pos, initCount)
        }, 200)
      }
      else{
        clearTimeout(scrollTimer)
      }
    },
    // 滚动聊天列表到底部
    scrollChatListDown: (pos, initCount) => {
      let dom = document.getElementById('chat-list')
      if (!dom) {
        return
      }
      let maxCount = 5
      initCount = initCount || 1
      if (typeof pos !== 'number') {
        pos = Math.max(dom.scrollHeight - dom.clientHeight, 888888)
      }
      dom.scrollTop = pos
      if ((dom.scrollTop < pos) && (initCount < maxCount)) {
        clearTimeout(scrollTimer)
        scrollTimer = setTimeout(() => {
          initCount++
          page.scrollChatListDown(pos, initCount)
        }, 200)
      }
    },
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        let res = info.file.response.data;
        this.imageUrl = res.originalUrl;
      }
    },
    toPlay(){
      this.playFlag = true;
      // setTimeout(()=>{
      //   neplayer("my-video", {}, function(res){
      //     // 当播放器初始化完成时运行的回调函数
      //     console.log(res)
      //   });
      // }, 300)
        setTimeout(function(){
          player = videojs('myvideo', {}, function(){console.log('videojs播放器初始化成功')})
          player.play();
        }, 300)
    },
    goBack(){
      this.$router.push({ path: '/home'})
    },
    toSubmit(){}
  }
  
});
</script>

<style lang="scss" scoped>
@import "../../styles/variables";

.live-room {
  background: $gray-2;
  overflow-y: auto;
  overflow-x: hidden;
  height: 100vh;

  &__swipe {
    ::v-deep .van-swipe-item {
      color: #fff;
      font-size: 20px;
      line-height: 150px;
      text-align: center;
      background: #39a9ed;
      height: 138px;
    }
  }

  ::v-deep .van-tab--active {
    font-weight: bold;
  }
  .video-box{
    height:420px; background-color:#666; position: relative; overflow:hidden;
    .video-js{ width:100%; height:420px;}
    .cover{ width:100%;}
    .video-num{
      display: flex; justify-content: space-between; align-items: center; position:absolute; top:24px; left:0; z-index:100; height:60px; width:100%;
      .back{
        display: flex; justify-content: center; align-items: center; margin-left:24px;
        img{ width:60px; height:60px;}
      }
      .num{
        display: flex; justify-content: center; align-items: center; width:184px; height:52px; background-color:rgba(0, 0, 0, 0.4); border-radius:30px; font-size:20px; color:#fff; margin-right:24px;
        span{ margin-left:8px;}
      }
    }
    .play{
      width: 116px; height:116px; position:absolute; top:152px; left:318px; z-index:100;
      img{ width:100%; height:100%;}
    }
  }
  .video-text{
    height:44px; line-height:44px; background-color:#323333; color:#fff; font-size:24px;
  }
}
  .inner {
    margin-left: 100%;
    width: 200%;
    animation: myMove 20s linear infinite;
    animation-fill-mode: forwards;
    span{ margin-right:350px;}
  }
.top-boxs{
  display: flex; justify-content: flex-start; align-items: center; height:48px; margin:24px 24px 36px; background-color:#fff; border-radius:24px; white-space:nowrap; overflow:hidden; padding:0 24px; font-size:24px; color:#999;
  .top{ margin-left:20px; overflow:hidden;}
    /*文字无缝滚动*/
  @keyframes myMove {
    0% {
      transform: translateX(0);
    }
    100% {
      transform: translateX(-1000px);
    }
  }
}
.form-box{
  padding:24px;
  .form-tit{ 
    font-size:28px; line-height:40px; margin-bottom:16px; color:#2E2F33;
    .red{ color:#DB1919; line-height: 20px;}
  }
  .form-li{
    padding: 0 24rpx; background-color:#DB1919; height:96rpx; border-radius:48px; font-size:28px; display:flex; align-items:center; overflow:hidden; margin-bottom:30px;
  }
  .submit{ height:96px; width:100%; border-radius:48px;}
}
.chat-container {
  padding: 10px 24px 0;

  &__notice {
    border-radius: $border-radius-max;
    height: 24px;
    padding: 0 $padding-xs;
    margin-bottom: 10px;

    ::v-deep .van-notice-bar__left-icon {
      color: $gray-8;
    }
  }
  .top-box{
    display: flex; justify-content: flex-start; align-items: center; height:48px; margin:24px 0 36px; background-color:#fff; border-radius:24px; white-space:nowrap; overflow:hidden; padding:0 24px; font-size:24px; color:#999;
    .top{ margin-left:20px; overflow:hidden;}
  }
}
#chat-list{ height: 40vh; overflow-y:auto;}
.chat-action-bar {
  display: flex; justify-content: space-between; align-items: center;  margin-top:20px;
  margin-bottom: 20px;
  .chat-btn{
    display:flex; justify-content:center; align-items:center; width:74px; height:74px; background-color:#fff; border-radius:50%; overflow:hidden; position:relative;
  }
  .chat-btn-ml{ margin-left:24px;}
  .chat-input{
    display:flex; justify-content:center; align-items:center; margin-left:24px; height:74px; background-color:#fff; border-radius:36px; overflow:hidden;
    .van-cell{ padding:0 16px;}
  }
}

.leave-message__content{ width: 550px;}
.leave-message {
  margin-bottom: 36px;
  display: flex;

  &__content {
    margin-top: 10px;
    margin-left: 10px;
    text-align: left;
  }

  &__tag-admin {
    margin-left: 4px;
  }

  &__nickname {
    display: flex;
    align-items: center;
    color: #161f1c; margin-bottom:16px;
  }

  &__top {
    color: #cf4c5b;
    margin-right: 8px;
  }

  &__message {
    margin-top: 10px;
    display: inline-block;
    border: 1px solid #cf4c5b;
    padding: 8px 20px;
    color: #333333;
    background: $white;
    max-width: 80%;word-wrap: break-word
  }

  &__datetime {
    margin-top: 10px;
    display: block;
    color: $gray-6;
    font-size: $font-size-sm;
  }

  &__actions {
    margin-top: 10px;
    display: block;
  }

  &__action {
    font-size: $font-size-sm;
    margin-right: 24px;
    color: $gray-6;

    &:last-child {
      margin-right: 0;
    }

    &--top {
      color: $orange-dark;
    }
  }
  .leave-message__message{ border-radius:5px;}
}
.red-box{
  width:62px; position:fixed; bottom:350px; right:26px; z-index:4;
  img{ width:62px; height: 80px;}
}
</style>
